
using Microsoft.EntityFrameworkCore;
using Admin2024.EntityFrameworkCore;
using Admin2024.Domain.Interface;
using Admin2024.EntityFrameworkCore.Repository;
using Admin2024.Domain.DomainService.System.UserService;
using Admin2024.Application.Contracts.User;
using Admin2024.Domain.ObjValue;
using Admin2024.Domain.DomainService.System;
using Admin2024.Domain.IDomainService.System.IUserService;
using Admin2024.Application.User;
using Admin2024.Application.Contracts.Helper;
using Admin2024.Domain.IDomainService.System.IRoleService;
using Admin2024.Domain.DomainService.System.RoleService;
using Admin2024.Application.Contracts.Role;
using Admin2024.Application.Role;
using Admin2024.Domain.IDomainService.System.IPermissionService;
using Admin2024.Domain.DomainService.System.PermissionService;
using Admin2024.Application.Contracts.Permission;
using Admin2024.Application.Permission;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Admin2024.Infrastructure.Middleware;
using Admin2024.Domain.IDomainService;
using Admin2024.Application.Contracts.FileUpload;
using Admin2024.Domain.Entity.System;
using Admin2024.Application.FileUpload;
using Microsoft.Extensions.Configuration;
using Serilog;
using Admin2024.Api.Filter;

namespace Admin2024.Api;

public class Startup
{
    private readonly IConfiguration Configuration;

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    public void Configure(IApplicationBuilder app)
    {

        app.UseDeveloperExceptionPage();
        //app.UseMiddleware<RequestHeaderMiddleware>();
        app.UseRouting();
        app.UseAuthentication(); //方法启用认证中间件。
        app.UseAuthorization(); //方法启用授权中间件。


        app.UseCors("AllowAll");
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
      
        // 配置Swagger中间件
        app.UseSwagger();

        app.UseSwaggerUI(c =>
   {
       c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
       c.RoutePrefix = "swagger"; // Swagger UI will be available at /swagger
   });

    }

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddControllers();

        //获取上传文件配置

        var uploadfileSettings = Configuration.GetSection("UploadFilesSettings").Get<UploadFilesSettings>();
        uploadfileSettings ??= new UploadFilesSettings
        {
            FilePath = "UploadFiles/Images",
            AllowFileExtension = ["jpg", "jpeg", "png"],
            MaxFileSize = "10M"
        };
        // 将一个对象注册为单例服务
        services.AddSingleton(uploadfileSettings);
        //JWT
        var jwtSettings = Configuration.GetSection("JwtSettings").Get<JwtSettings>();
        jwtSettings ??= new JwtSettings { Issuer = "xyz", Audience = "xyz", SecretKey = "xyz" };
       
        // 读取JwtSettings配置
   
        Configuration.GetSection("JwtSettings").Bind(jwtSettings);
        services.AddSingleton(jwtSettings);

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            options.RequireHttpsMetadata = false;
            options.SaveToken = true;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = jwtSettings.Issuer,
                ValidAudience = jwtSettings.Audience,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey))
            };
        });
        services.AddSingleton(jwtSettings);
        

        services.AddAuthorization();

        // 添加授权服务，但不需要添加任何策略
    
        services.AddScoped<IJwtService, JwtService>();
        services.Configure<JwtSettings>(Configuration.GetSection("JwtConfig"));
        // 跨域
        services.AddCors(options =>
        {
            options.AddPolicy("AllowAll", builder =>
            {
                builder.AllowAnyOrigin()
                         .AllowAnyMethod()
                         .AllowAnyHeader();
            });
        });
          
        services.AddDbContext<Admin2024DbContext>(opt =>
        {
            opt.UseNpgsql(Configuration.GetConnectionString("Pg"));
        });


        //中间件
        //services.AddTransient<RequestHeaderMiddleware>();
        //过滤器注册
        services.AddScoped<CtmAuthorizationFilterAttribute>();

        services.AddSwaggerGen();
        services.AddScoped(typeof(IRepository<>), typeof(EFRepository<>));
        services.AddScoped(typeof(IBaseDomainService<>), typeof(BaseDomainService<>));
        //AutoMapper注入
        services.AddAutoMapper(typeof(UserAutoMapperProfile).Assembly);
        //服务注册

        services.AddScoped(typeof(IFileUploadService),typeof(FileUploadService));
        services.AddScoped(typeof(IAppFileUploadService),typeof(AppFileUploadService));

        services.AddScoped(typeof(IAuthenticationService), typeof(AuthenticationService));
        services.AddScoped<IUserServer, UserServer>();

        services.AddScoped(typeof(IUserProfileService), typeof(UserProfileService));
        services.AddScoped<IUserInfoService, UserInfoService>();

        services.AddScoped(typeof(IUserStateManager), typeof(UserStateManager));
        services.AddScoped<IUserStateService, UserStateService>();


        services.AddScoped(typeof(IPasswordManagementService), typeof(PasswordManagementService));
        services.AddScoped<IPasswordService, PasswordService>();  

        //用户角色管理服务
        services.AddScoped(typeof(IUserRoleManagementService), typeof(UserRoleManagementService));
        services.AddScoped<IAppUserRoleService,AppUserRoleService>();


        //角色信息服务
        services.AddScoped(typeof(IRoleProfileService), typeof(RoleProfileService));
        services.AddScoped<IRoleInfoService, RoleInfoService>();
        //角色状态服务
        services.AddScoped(typeof(IRoleStateManager), typeof(RoleStateManager));
        services.AddScoped<IRoleStateService, RoleStateService>();
        //角色权限服务
        services.AddScoped(typeof(IRolePermissionAssignService),typeof(RolePermissionAssignService));
        services.AddScoped<IRolePermissionService, RolePermissionService>();

        services.AddScoped(typeof(IPermissionManagementService), typeof(PermissionManagementService));
        services.AddScoped(typeof(IOperationManagementService), typeof(OperationManagementService));
        services.AddScoped(typeof(IResourceManagementService), typeof(ResourceManagementService));

        services.AddScoped<IPermissionService, PermissionService>();


      

    }
}